const mongoose = require('mongoose')
const jwt = require('jsonwebtoken')
const User = mongoose.model('user')
const msgUser = mongoose.model('msgUser')
const Group = mongoose.model('group')
const msgGroup = mongoose.model('msgGroup')
const request = require('request')
const config = require('../config')
const { formatBody } = require('../tools')

module.exports = {
  async newMessage (info, socket, cb, io) {
    let { type, from, content, to, msgType } = info
    if(type === 'private') { // 私聊
      let target = await User.findOne({ _id: to })
      .populate('socket','socket_id')
      if (!target) return cb(formatBody(0, '目标不存在'))
      let newMsg = await new msgUser({
        to, content, msgType,
        from: from._id,
        createAt: Date.now()
      }) 
      // 如果对方在线
      if(target.onlineState && target.socket) {
        let msg = {
          from, to, content, msgType, type,
          createAt: newMsg.createAt,
          _id: newMsg._id
        }
        io.to(target.socket.socket_id).emit('new message', msg)   
      }
      await newMsg.save()
      return cb(formatBody(1, '发送成功'))
    } else if (type === 'group') { // 群聊
      let group = await Group.findOne({_id: to})
      let newMsg = await new msgGroup({
        content,
        from: from._id,
        to,
        msgType,
        createAt: Date.now()
      })
      socket.broadcast.to(to).emit('new message', {
        from, to, content, type, msgType,
        createAt: newMsg.createAt,
        _id: newMsg._id
      })
      await Group.update({
        _id: to
      }, {
        $set: { lastWord: newMsg._id }
      })
      await newMsg.save()
      return cb(formatBody(1, '发送成功', newMsg))
    } else if (type === 'robot') { // 图灵机器人
      // console.log(config)
      let { content, from } = info
      let { api, apiKey } = config.tuRing
      request.post({
        url: api,
        form: {
          key: apiKey,
          info: content
        }
      }, (err, httpResponse, body) => {
        if (err) {
          return cb(formatBody(0, 'error', err))
        } else {
          return cb(formatBody(1, 'ok', body))
        }
      })
    } else if (type === 'random') { // 随机匹配的消息
      let { type, from, content, to, msgType } = info
      let target = await User.findOne({ _id: to })
      .populate('socket','socket_id')
      from.nickname = '陌生人'
      from.avatar = ''
      if(target.onlineState && target.socket) {
        let msg = {
          from, to, content, msgType, type,
          createAt: Date.now()
        }
        io.to(target.socket.socket_id).emit('new message', msg)   
      }
      return cb(formatBody(1, '发送成功'))
    } else {
      return cb(formatBody(0, '未知消息类型'))
    }
  },

  async getPrivateMsg (info, socket, cb) {
    let { from, to, timestamp, limit } = info
    timestamp = timestamp ? timestamp : Date.now()
    let historys = await msgUser
    .find({
      $or: [{ 'from': from, 'to': to }, { 'to': from, 'from': to }],
      createAt: { $lt: timestamp }
    })
    .sort({'_id': -1})
    .limit(limit || 20)
    .populate('from', 'avatar nickname _id')
    historys.reverse()
    return cb(formatBody(1, 'ok', historys))
  },

  async getGroupMsg (info, socket, cb) {
    let { to, timestamp, limit } = info
    timestamp = timestamp ? timestamp : Date.now()
    let historys = await msgGroup
    .find({
      to,
      createAt: { $lt: timestamp }
    })
    .sort({'_id': -1})
    .limit(limit || 20)
    .populate({
      path: 'from',
      select: 'avatar nickname _id'
    })
    historys.reverse()
    return cb(formatBody(1, 'ok', historys))
  }
}


